package com.jc.oms.shiro;

import com.jc.business.rolepermission.RolePermissionBusiness;
import com.jc.business.user.UserBusiness;
import com.jc.business.userrole.UserRoleBusiness;
import com.jc.ds.model.User;
import com.jc.framework.enums.UserStatus;
import com.jc.framework.util.SpringUtils;
import com.jc.service.user.UserService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.List;
import java.util.Set;

public class CustomRealm extends AuthorizingRealm {

		private UserService userService = SpringUtils.getBean(UserService.class);
		
		private UserBusiness	 userBusiness = SpringUtils.getBean(UserBusiness.class);
		
		
		private UserRoleBusiness userRoleBusiness = SpringUtils.getBean(UserRoleBusiness.class);
		
		
		private RolePermissionBusiness rolePermissionBusiness = SpringUtils.getBean(RolePermissionBusiness.class);;
		
		

	    /**
	     * 必须重写此方法，不然会报错
	     */
	    @Override
	    public boolean supports(AuthenticationToken token) {
	        return token instanceof JWTToken;
	    }

	    
	    /**
	     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
	     */
	    @Override
	    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
	        System.out.println("————权限认证————");
	        String username = JWTUtil.getUsername(principals.toString());
	        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
	        User _u = new User();
	        _u.setUserName(username);
	        _u.setIsDelete(0);
	        List<User> list = userService.queryAll(_u);
	        if(CollectionUtils.isEmpty(list)) {
	        	throw new RuntimeException(" 鉴权异常 用户" + username + " 不存在!");
	        }
	        if(list.size() > 1) {
	        	throw new RuntimeException(" 鉴权异常 用户" + username + " 存在多条记录 !");
	        }
	        User cSysUser = list.get(0);
	        if(StringUtils.equals(cSysUser.getIsEnable(), UserStatus.LOCK.getName())) {
	        	throw new RuntimeException(" 鉴权异常 用户" + username + " 目前是锁定状态 !");
	        }
	        //存储roid列表
			Set<String> shiro_user_roles = userRoleBusiness.getUserRoleListByUserId(cSysUser.getId());
			info.setRoles(shiro_user_roles);
			//存储资源URL列表
			Set<String> shiro_user_permissions = rolePermissionBusiness.getUserPermissionListByUserId(cSysUser.getId());
			info.setStringPermissions(shiro_user_permissions);
	        return info;
	    }
	    
	    
	    
	    /**
	              * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
	              *   如果后期出现性能问题这个地方修改为REDIS缓存查询
	     */
	    @Override
	    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
	        System.out.println("————身份认证方法————");
	        String token = (String) authenticationToken.getCredentials();
	        // 解密获得username，用于和数据库进行对比
	        String username = JWTUtil.getUsername(token);
	        if (username == null || !JWTUtil.verify(token, username)) {
	            throw new AuthenticationException("token认证失败！");
	        }
	       
	        User _u = new User();
	        _u.setUserName(username);
	        _u.setIsDelete(0);
	        List<User> list = userService.queryAll(_u);
	        if(CollectionUtils.isEmpty(list)) {
	        	throw new AuthenticationException(" 鉴权异常 用户" + username + " 不存在!");
	        }
	        if(list.size() > 1) {
	        	throw new AuthenticationException(" 鉴权异常 用户" + username + " 存在多条记录 !");
	        }
	        User cSysUser = list.get(0);
	        if(StringUtils.equals(cSysUser.getIsEnable(), UserStatus.LOCK.getName())) {
	        	throw new AuthenticationException(" 鉴权异常 用户" + username + " 目前是锁定状态 !");
	        }
	        	        
	        return new SimpleAuthenticationInfo(token, token, "MyRealm");
	    }

	    

}
